package com.ibuu.fiflter;

import com.alibaba.fastjson.JSON;

import com.ibuu.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(filterName = "loginfilter", urlPatterns = "/front/*")
@Slf4j
public class Loginfilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        String uri = req.getRequestURI();

        boolean check = check(uri);

        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        log.info("拦截uri uri={}" + uri);
        Object user = session.getAttribute("username");


        if (user != null) {
            log.info("用户已登录 用户名为user={}" + user);
            BaseContext.selectid(user.toString());
            filterChain.doFilter(request, response);
            return;
        }

        response.getWriter().write(JSON.toJSONString("NOTLOGIN"));
    }

    private boolean check(String uri) {
        String[] urls = new String[]{
                "/user/login",
                "/user/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/plugins/**",
                "/image/**",
                "/favicon.ico",



        };
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match) {
                log.info("放行uri为 uri={}" + uri);
                return true;
            }
        }
        return false;
    }


}


